package com.nix.email;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.junit.Test;

import java.io.IOException;

/**
 * 参考网址 http://www.jb51.net/article/56793.htm
 * Create by zhangpe0312@qq.com on 2017/12/31.
 */
public class ApacheMailSendSimpleEmail extends ApacheMail implements EmailService {

    private String subject = "情绪分析团队通知";
    private String msg = "";
    private String toAddress = "";
    private String toName = "";

    public ApacheMailSendSimpleEmail(String toAddress, String toName) throws IOException {
        super();
        this.toAddress = toAddress;
        this.toName = toName;
    }

    public ApacheMailSendSimpleEmail() throws IOException {
        super();
    }

    @Override
    public void sendEmail() throws EmailException {
        sendEmail(toAddress, toName);
    }

    @Override
    public void accept() {

    }

    @Override
    void sendEmail(String toAddress, String toName) throws EmailException {
        SimpleEmail email = new SimpleEmail();
        email.setHostName(hostName);
        email.setAuthentication(name, password);
        email.setCharset("utf-8");
        email.setFrom(fromAddress, fromName,"utf-8");
        email.addTo(toAddress,toName,"utf-8");
        email.setSubject(subject);
        email.setMsg(msg);
        email.send();
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getToName() {
        return toName;
    }

    public void setToName(String toName) {
        this.toName = toName;
    }

    public static void main(String[] args) {
        String email = "zhangpe0312@qq.com";
        String ecode = "123456";
        ApacheMailSendSimpleEmail sendEmail;
        try {
            sendEmail = new ApacheMailSendSimpleEmail(email,"亲爱的情绪分析朋友！");
            sendEmail.setMsg("你申请的验证码为：" + ecode);
            sendEmail.setSubject("找回密码验证码-情绪分析团队");
            sendEmail.setToAddress(email);
            sendEmail.setToName("你好！");
            try {
                sendEmail.sendEmail();
            } catch (EmailException e) {
                System.out.println("发送邮件失败" + e);
            }
        } catch (IOException e) {
            System.out.println("发送信息失败！" + e);
        }
    }
}

